package com.startasone.aop;

import com.alibaba.fastjson.JSONObject;
import com.startasone.Utlis.JwtUtils;
import com.startasone.mapper.OperateLogMapper;
import com.startasone.pojo.OperateLog;
import io.jsonwebtoken.Claims;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {
    @Autowired
    private OperateLogMapper operateLogMapper;
    @Autowired
    private HttpServletRequest request;

    @Around("@annotation(com.startasone.pojo.MyLog)")
    public Object LogOperate(ProceedingJoinPoint joinPoint) throws Throwable {
        String Jwt=request.getHeader("token");
        Claims claims = JwtUtils.parseJWT(Jwt);
        Integer operateUser = (Integer) claims.get("id");
        LocalDateTime operateTime = LocalDateTime.now();
        String className = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();
        String methodParam = Arrays.toString(joinPoint.getArgs());
        Long startTime = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        String returnValue = JSONObject.toJSONString(result);
        Long endTime = System.currentTimeMillis();
        Long costTime = endTime - startTime;
        OperateLog operateLog = new OperateLog(null, operateUser, operateTime, className, methodName, methodParam, returnValue, costTime);
        operateLogMapper.insert(operateLog);
        return result;
    }

}
